/**
 * 应用 启动
 */
export function bootApp () {
  console.log('【Boot App】')
  if (uni.flux.store.state.env.isWeixin) {
    return bootAppForWechat()
  } else {
    return bootAppForH5()
  }
}
/**
 * 启动H5
 */
export function bootAppForH5 () {
  // uni.flux.$api.user.addUnionId()
  uni.flux.$api.user.getShareParamByOfficialId()
  const { route } = uni.flux.utils.getCurrentPageFullPath()
  // H5pdf & 聚合页
  if (route) {
    // 聚合页
    if (route === '/pages/aggregation/index') {
      // 聚合页每次必须调token
      return h5LoginInit()
    }
  }
  // 白名单
  const whiteNameList = [
    '/pages/mine/login/index',
    '/pages-h5/hanzi-write/index',
    '/pages-h5/calculator/index',
    '/pages/pdf/test-paper/index',
    '/pages/pdf/index/index'
  ]
  if (route && whiteNameList.includes(route)) {
    return uni.flux.isLogined()
  }
  return initLogin()
}

/**
 * 启动微信小程序
 */
export function bootAppForWechat () {
  const { route } = uni.flux.utils.getCurrentPageFullPath()
  const whiteNameList = [
    '/pages/mine/login/index',
    '/pages/pdf/test-paper/index',
    '/pages/pdf/index/index',
    '/pages-h5/webView/index'
  ]
  if (route && whiteNameList.includes(route)) {
    return uni.flux.isLogined()
  }
  return initLogin()
}

// 登录
export function initLogin () {
  const token = uni.flux.store.state.token
  // 微信小程序
  if (uni.flux.store.state.env.isWeixin) {
    // 有token 都要调???
    if (token) {
      return uni.flux.$api.user.getReaderInfo()
    } else {
      return uni.flux.$api.user.getTokenInfo()
    }
  } else {
    // H5
    if (token) {
      return uni.flux.$api.user.getReaderInfo()
    } else {
      return h5LoginInit()
    }
  }
}

export function h5LoginInit () {
  return new Promise((resolve, reject) => {
    if (uni.flux.store.state.env.isDev) {
      // H5本地开发用的接口
      return uni.flux.$api.user.loginByPhone()
    } else {
      return uni.flux.$api.user.h5Authorize()
    }
  })
}
